package com.ali.juejin.adapter

import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat.startActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.ali.juejin.BR
import com.ali.juejin.R
import com.ali.juejin.base.BaseFragment
import com.ali.juejin.bean.home.followItem.Entrylist
import com.ali.juejin.ui.activity.ArticleDetailActivity
import com.ali.juejin.ui.activity.LoginActivity
import com.blankj.utilcode.util.LogUtils
import kotlinx.android.synthetic.main.item_home_follow.view.*
import kotlinx.android.synthetic.main.item_login.*
import kotlinx.android.synthetic.main.item_login.view.*

class HomeFollowAdapter<K:ViewDataBinding,V:BaseFragment>(val context: V): RecyclerView.Adapter<HomeFollowAdapter.HomeFollowHolder<K>>() {

    private var list = ArrayList<Entrylist>()

    class HomeFollowHolder<T:ViewDataBinding>(val databind: T) : RecyclerView.ViewHolder(databind.root){
        fun getBinding():T{
            return databind
        }
    }

    fun fresh(params:ArrayList<Entrylist>){
        list.clear()
        list.addAll(params)
//        LogUtils.w(list.size)
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        if(position == 0){
            return 1
        }
        return 0
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeFollowHolder<K> {
        if(viewType ==1){
            // 显示顶部登录状态的内容
            return HomeFollowHolder(DataBindingUtil.inflate(LayoutInflater.from(context.context), R.layout.item_login,parent,false))
        }
        return HomeFollowHolder(DataBindingUtil.inflate(LayoutInflater.from(context.context), R.layout.item_home_follow,parent,false))
    }

    override fun getItemCount(): Int {
        return list.size+1
    }


    override fun onBindViewHolder(holder: HomeFollowHolder<K>, position: Int) {
        if(position == 0){
            holder.itemView.item_login_btn.setOnClickListener {
                startActivity(context.context!!,Intent(context.context,LoginActivity::class.java),null)
            }
            return
        }

        val itemData = list[position-1]
        holder.itemView.item_home_follow_recommend_btn.setOnClickListener {
            if(context.interceptLogin()){
                LogUtils.wTag("关注按钮","已登录")
            }
        }
        holder.itemView.item_home_follow_recommend_con.setOnClickListener {
            startActivity(context.context!!,
                Intent(context.context,ArticleDetailActivity::class.java).putExtra("id",itemData.objectId),
                null
            )
        }
        val binding = holder.getBinding()
        binding.setVariable(BR.HomeFollow,itemData)
        binding.executePendingBindings()
    }

}